package com.adhere.system.controller;

import com.adhere.system.pojo.RbacUserRole;
import com.adhere.system.pojo.dto.UserRoleDto;
import com.adhere.system.service.IRbacUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户与角色关系管理
 */
@RestController
@RequestMapping("/user/role")
public class UserRoleController {

    @Autowired
    private IRbacUserRoleService userRoleService;

    /**
     * 给用户添加角色信息
     * @param userRoleDto
     */
    @PostMapping("/")
    public void addUserRole (@RequestBody @Validated UserRoleDto userRoleDto) {
        List<String> roleCodeList = userRoleDto.getRoleCodeList();
        String userCode = userRoleDto.getUserCode();

        if (ObjectUtils.isEmpty(roleCodeList)) {
            throw new IllegalArgumentException("传入的角色code不能为空");
        }

        //todo 验证当前用户是否已经拥有这些角色

        roleCodeList.forEach(roleCode -> {
            RbacUserRole rbacUserRole = new RbacUserRole().setRoleCode(roleCode).setUserCode(userCode);
            //
            userRoleService.save(rbacUserRole);
        });

    }

    /**
     * 更新用户拥有的角色信息
     * @param userRoleDto
     */
    @PutMapping("/")
    public void updateUserRole(@RequestBody @Validated UserRoleDto userRoleDto) {
        userRoleService.updateUserRole(userRoleDto);
    }


}
